<template>
  <el-dialog v-model="isShowDialog" :title="updateForm.id ? '编辑' : '注册'" width="600" :before-close="closeDialog">
    <!-- 校验规则为rules，直接定义所有参数的rules，但是<el-form-item>中的prop还是要设置，且还需要新增一个interface -->
    <el-form ref="updateFormRef" :model="updateForm" :rules="passwordRules">
      <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName" :rules="[
        { required: true, message: '用户名不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="updateForm.userName" placeholder="请输入用户名" :disabled="updateForm.id != null"/>
      </el-form-item>
      <el-form-item label="姓名" :label-width="formLabelWidth" prop="realName" :rules="[
        { required: true, message: '姓名不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="updateForm.realName" placeholder="请输入姓名"/>
      </el-form-item>

      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email" :rules="[
        { required: true, message: '邮箱不能为空', trigger: 'blur' },
        { pattern: '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$', message: '邮箱格式不正确', trigger: 'blur'}
      ]">
        <el-input v-model="updateForm.email" placeholder="请输入邮箱">
          <template #append v-if="!updateForm.id">
            <el-button @click="getVerifyCode()" :disabled="!showVerifyButton">
              <span v-show="showVerifyButton">获取验证码</span>
              <span v-show="!showVerifyButton" class="count">{{ count }} s</span>
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="!updateForm.id" label="验证码" :label-width="formLabelWidth" prop="verifyCode" :rules="[
        { required: true, message: '验证码不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="updateForm.verifyCode" placeholder="请输入验证码"/>
      </el-form-item>
      <el-form-item v-if="!updateForm.id" label="密码" :label-width="formLabelWidth" prop="password" :rules="[
        { required: true, message: '密码不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="updateForm.password" show-password placeholder="请输入包含英文字母大小写、数字和特殊符号的 6-20 位组合"/>
      </el-form-item>
      <el-form-item v-if="!updateForm.id" label="确认密码" :label-width="formLabelWidth" prop="passwordbak" :rules="[
        { required: true, message: '确认密码不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="updateForm.passwordbak" show-password placeholder="请再次输入密码"/>
      </el-form-item>
      <el-form-item v-if="updateForm.id" label="角色" :label-width="formLabelWidth" prop="roleIdList" :rules="[
        { required: true, message: '角色不能为空', trigger: 'blur' }
      ]">
        <el-select v-model="updateForm.roleIdList" multiple placeholder="请选择角色" >
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm(updateFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive,ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElLoading } from 'element-plus';
import { post, postWithToken } from '~/composables/utils';
// 回调父页面
const emit = defineEmits(['refresh']);
const updateFormRef = ref<FormInstance>();
const count = ref<number>(60);
// 展示弹框的参数
const isShowDialog = ref(false);
// 显示获取验证码和倒计时
const showVerifyButton = ref(true);
// 弹框里面label的宽度
const formLabelWidth = '80px';
const roleList = ref<any>();
// 弹框里面的form
const updateForm = reactive<UpdateUserForm>({
    id:null,
    userName: '',
    realName:'',
    email: '',
    verifyCode: '',
    password: '',
    passwordbak: '',
    roleIdList:[]
});
// 弹框里面的form对应的interface
interface UpdateUserForm {
  id:number | null | undefined;
  userName: string;
  realName:string;
  email:string;
  verifyCode:string;
  password:string;
  passwordbak:string;
  roleIdList:[];
}
// 校验密码
const validatePass = (rule: any, value: any, callback: any) => {
  const passReg = /^[^\s\u4e00-\u9fa5]{6,20}$/;
  if (!passReg.test(value)) {
    callback(new Error('请输入包含英文字母大小写、数字和特殊符号的 6-20 位组合'))
  } else {
    if (updateForm.password !== '') {
      if (!updateFormRef.value) return
      updateFormRef.value.validateField('password')
    }
    callback()
  }
}
// 校验重复密码
const validatePassbak = (rule: any, value: any, callback: any) => {
 if (value !== updateForm.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

const passwordRules = reactive<FormRules<typeof updateForm>>({
  password: [{ validator: validatePass, trigger: 'blur' }],
  passwordbak: [{ validator: validatePassbak, trigger: 'blur' }],
})

const submitUpdateForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      addOrUpdateUser();
    } else {
      console.log('error submit!')
    }
  })
};

// 新增更新数据
const addOrUpdateUser =  async () => {
  try {
    const loadingInstance = ElLoading.service({fullscreen: true});
    var response ;
    if (updateForm.id) {
      response = await postWithToken('/user/updateUser', updateForm);
    } else {
      response = await post('/user/saveUser', updateForm);
    }
    loadingInstance.close();
    if (response.code != 200) {
        ElMessage.error(response.msg);
    } else {
        ElMessage.success((updateForm.id ? '修改' : '注册') + '用户成功！');
        closeDialog();
    }
  } catch (error) {
    console.error('There was an error!', error);
  }
};

function closeDialog() {
  isShowDialog.value = false;
  clearForm();
  // 回调父页面的@refresh，刷新页面
  emit('refresh');
}
// 重置数据
const clearForm = () => {
  updateForm.id = null;
  updateForm.email = '';
  updateForm.userName = '';
  updateForm.realName = '';
  updateForm.password = '';
  updateForm.verifyCode = '';
  updateForm.passwordbak = '';
  updateForm.roleIdList = [];
}

const getVerifyCode = () => {
  if (!updateFormRef.value) {
    return;
  }
  updateFormRef.value.validateField('email', (valid) => {
    if (valid) {
      post('/user/getVerifyCode', { 'email': updateForm.email})
      .then(response => {
        if (response.code != 200){
          ElMessage.error(response.msg);
        }
      });
      count.value = 60;
      showVerifyButton.value = false;
      const timer = setInterval(() => {
        if (count.value > 0 && count.value <= 60) {
          count.value --;
        } else {
          showVerifyButton.value = true;
          clearInterval(timer);
        }
      }, 1000);
    }
  });
}

const listRole = async (userId ?: number | null) => {
  var response = await postWithToken('/role/listRole', {"userId" : userId});
  if (response.code != 200) {
    ElMessage.error(response.msg);
  } else {
    // 所有的角色
    roleList.value = response.data;
    // 已选择的角色
    updateForm.roleIdList = response.data.filter((item:any) => item.selected).map((item:any) => item.id);
  }
}

const init = (data?: UpdateUserForm) => {
  isShowDialog.value = true;
  if (data) {
    Object.assign(updateForm, data);
    listRole(updateForm.id);
  }
};
defineExpose({ init });
</script>
<style lang="scss">
/* 为了页面刷新不出现滚动条 */
.ep-scrollbar {
  height: auto;
}
</style>